<template>
  <div class="button" @click="show">添加</div>

  <el-dialog
    width="680px"
    v-model="visible"
    title="知识库选择"
    :close-on-click-modal="false"
    destroy-on-close
    append-to-body
  >
    <div style="width: 300px;margin-bottom: 20px">
      <el-input v-model="filterName" placeholder="输入知识库名称进行搜索" />
    </div>
    <div class="dialog-body">
      <div
        v-for="(data, index) in dataList"
        :key="index"
        :class="['item-box', data.selected ? 'selected' : '']"
        @click="data.selected = !data.selected"
      >
        <div class="name" :title="data.name">{{data.name}}</div>
      </div>
    </div>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="visible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        @click="submit"
      >确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import api from "@/http/api";

const selectedList = defineModel();
const allList = ref([]);
const dataList = ref([]);
const visible = ref(false);
const filterName = ref('');

const show = () => {
  visible.value = true;
  if (!selectedList.value || selectedList.value.length === 0) return;
  (allList.value || []).forEach(data => {
    const selected = selectedList.value.find(item => item.id === data.id);
    data.selected = !!selected;
  });
  filterMethod();
};

const filterMethod = () => {
  if (!filterName.value) {
    dataList.value = allList.value;
  }
  dataList.value = allList.value.filter(item => item.name.indexOf(filterName.value) >= 0);
};

const submit = () => {
  selectedList.value = allList.value
    .filter(item => item.selected)
    .map(item => ({id: item.id, name: item.name}));
  visible.value = false;
};

const loadDataList = () => {
  api.post('/system/knowledge/queryList').then(res => {
    allList.value = res.data || [];
    filterMethod();
  });
};

watch(() => filterName.value, () => {
  filterMethod();
});

onMounted(() => {
  loadDataList();
});
</script>

<style scoped>
.button {
  cursor: pointer;
  color: #2E70FF;
}
.dialog-body {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.item-box {
  border: 1px solid #d5d6d9;
  border-radius: 5px;
  padding: 15px 20px;
  cursor: pointer;
  .name {
    width: 160px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.item-box.selected {
  border: 1px solid rgb(51, 112, 255);;
}
</style>